from django_filters.rest_framework import FilterSet, CharFilter, NumberFilter
from ai.models import Services, Models
from ai.serializers import ServicesSerializer, ServicesCreateUpdateSerializer
from dvadmin.utils.json_response import DetailResponse
from dvadmin.utils.viewset import CustomModelViewSet




class ServiceFilterSet(FilterSet):
    name = CharFilter(field_name="name", lookup_expr="contains")
    creator_id = NumberFilter(field_name="creator_id", lookup_expr="exact")
    type = NumberFilter(field_name="type", lookup_expr="exact")
    status = NumberFilter(field_name="status", lookup_expr="exact")

class ServicesView(CustomModelViewSet):
    """
        服务管理接口
        list:查询
        create:新增
        update:修改
        retrieve:单例
        destroy:删除
        """
    queryset = Services.objects.all()
    serializer_class = ServicesSerializer
    create_serializer_class = ServicesCreateUpdateSerializer
    update_serializer_class = ServicesCreateUpdateSerializer
    filter_fields = ['creator_id']
    filterset_class = ServiceFilterSet

    def create(self, request, *args, **kwargs):
        model = Models.objects.get(id=request.data["model"])
        model.is_published = 1  # 修改模型服务发布状态
        model.save()  # update方法
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        serializer.save()  # create方法
        return DetailResponse(data=serializer.data, msg="新增成功")
